import {eFrameMode, iMicroConfig, iMicroTokenInfo} from "@peryl/micro-web";
import {designComponent, PropType, watch} from "@peryl/react-compose";
import {microApp} from "../microApp";
import {FrameModeNone} from "./FrameModeNone";
import {FrameModeFrame} from "./FrameModeFrame";
import {FrameModeIFrame} from "./FrameModeIFrame";
import {useIndexLoader} from "./useIndexLoader";
import {useCurrentMicroConfig} from "./useCurrentMicroConfig";
import {useMicroLoading} from "./useMicroLoading";
import {$notice} from "plain-design";

export const MicroItem = designComponent({
  name: 'render-micro',
  props: {
    microConfig: { type: Object as PropType<iMicroConfig>, required: true },
    tokenInfo: { type: Object as PropType<iMicroTokenInfo>, required: true },
    active: { type: Boolean }
  },
  setup({ props }) {

    const { errors } = useMicroLoading(props.microConfig);

    /*iframe模式单独处理加载*/
    if (props.microConfig.iframe) {return () => <FrameModeIFrame microConfig={props.microConfig} tokenInfo={props.tokenInfo}/>;}

    const indexLoader = useIndexLoader({ microConfig: props.microConfig, tokenInfo: props.tokenInfo, });

    useCurrentMicroConfig.inject({ props, getIndexData: () => indexLoader.state.indexData });

    /*监听active变化，如果子应用从隐藏变为展示，但是加载不成功，这里每次展示都打印加载子应用失败的信息*/
    watch(() => props.active, (newActive, oldActive) => {
      if (!oldActive && !!newActive) {!!errors[props.microConfig.id] && $notice.error(errors[props.microConfig.id]!);}
    });

    return () => {
      return (
        !!indexLoader.state.indexData && (() => {
          const indexData = indexLoader.state.indexData;
          if (indexData.frameMode === eFrameMode.none) {
            return <FrameModeNone tokenInfo={props.tokenInfo} indexData={indexData} microApp={microApp}/>;
          } else if (indexData.frameMode === eFrameMode.frame) {
            return <FrameModeFrame tokenInfo={props.tokenInfo} indexData={indexData} microApp={microApp}/>;
          }
        })()
      );
    };
  },
});

